package com.two.screen.water.balance.ui.activity

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Intent
import android.graphics.Typeface
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.SimpleItemAnimator
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.chad.library.adapter.base.BaseItemDraggableAdapter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.jakewharton.rxbinding2.view.RxView
import com.two.screen.water.balance.R
import com.two.screen.water.balance.bean.BaseBean
import com.two.screen.water.balance.bean.WeightBean
import com.two.screen.water.balance.bean.water.LocalOrderBean
import com.two.screen.water.balance.bean.water.PayResultBean
import com.two.screen.water.balance.bean.water.ProductBean
import com.two.screen.water.balance.image.ImageManger
import com.two.screen.water.balance.listener.OnMyKeyCallBack
import com.two.screen.water.balance.net.api.DataApi
import com.two.screen.water.balance.net.api.NormalApi24
import com.two.screen.water.balance.net.observer.DialogObserver
import com.two.screen.water.balance.net.observer.NormalObserver
import com.two.screen.water.balance.net.observer.StatusLayoutObserver
import com.two.screen.water.balance.serial.weight.WeightAll
import com.two.screen.water.balance.ui.activity.LoginActivity24.Companion.LOGIN_ID_TYPE_BUYER
import com.two.screen.water.balance.ui.activity.LoginActivity24.Companion.LOGIN_ID_TYPE_SELLER
import com.two.screen.water.balance.ui.activity.base.BaseActivity
import com.two.screen.water.balance.ui.service.AppService
import com.two.screen.water.balance.utils.*
import com.two.screen.water.balance.utils.UtilsBigDecimal.DECIMAL_POINT_NUMBER1
import com.two.screen.water.balance.utils.UtilsBigDecimal.toDoubleWithTwoDecimalPlaces
import com.two.screen.water.balance.utils.eventbus.Event
import com.two.screen.water.balance.utils.eventbus.EventBusUtil
import com.two.screen.water.balance.utils.eventbus.EventCode
import com.two.screen.water.balance.utils.eventbus.EventCode.Companion.HANG_SUCCESS
import com.two.screen.water.balance.widget.dialog.EditProductInfoDialog
import com.two.screen.water.balance.widget.dialog.SelectedBatchDialog
import com.two.screen.water.balance.widget.statueslayoutmanager.DefaultOnStatusChildClickListener
import com.two.screen.water.balance.widget.statueslayoutmanager.StatusLayoutManager
import kotlinx.android.synthetic.main.activity_index24.*
import java.math.BigDecimal
import java.util.concurrent.TimeUnit


@Route(path = ARouterUtils.IndexActivity24)
class IndexActivity24 : BaseActivity() {
    val TAG = IndexActivity24::class.java.simpleName.plus("=>")
    override fun getContentLayout(): Any = R.layout.activity_index24

    /*列表适配器*/
    lateinit var mFoodAdapter: FoodAdapter
    lateinit var mHadChooseAdapter: HadChooseAdapter
    private var mCurFoodPageIndex = 0   //当前第几页数
    private var mPerPageMaxCount = 8  //一页当中最大的商品数据
    private var mTotalFoodList: MutableList<ProductBean>? = null//商品的总数据列表
    private var mTotalFoodMap: LinkedHashMap<Int, MutableList<ProductBean>> = linkedMapOf()//每个 页码对应的商品数据。
    private var mMaxPageCount = 0 //所有商品中，共分布多少页数。

    private var mIsStable = false//当前稳定状态
    private var mWeightDouble = 0.0 //重量
    private var mSelectedProductBean: ProductBean? = null//选中商品，接下来是“过称”
    private var mSelectedHadProductBean: ProductBean? = null//选中过称记录，接下来是“回皮，回毛，删除”
    private var mCurLocalOrderBean: LocalOrderBean = LocalOrderBean()

    /*对话框*/
    private var mSelectedBatchDialog: SelectedBatchDialog? = null
    private var mEditProductInfoDialog: EditProductInfoDialog? = null

    /*加载商品*/
    val mProductStatusLayoutManager: StatusLayoutManager by lazy {
        StatusLayoutManager.Builder(mProductLayout)
            .setLoadingLayout(R.layout.layout_status_layout_manager_loading)
            .setDefaultErrorClickViewVisible(setDefaultErrorClickViewVisible)
            .setDefaultEmptyClickViewVisible(setDefaultEmptyClickViewVisible)
            .setOnStatusChildClickListener(object : DefaultOnStatusChildClickListener() {
                override fun onEmptyChildClick(view: View?) {
                    getProductList()
                }

                override fun onErrorChildClick(view: View?) {
                    getProductList()
                }
            })
            .build()
    }

    override fun initView(savedInstanceState: Bundle?) {
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
        ARouter.getInstance().inject(this)
        mProductStatusLayoutManager.showSuccessLayout()
    }

    @SuppressLint("SetTextI18n")
    override fun initData() {
        mWeightTv.typeface = Typeface.createFromAsset(assets, "DS-DIGIT-4.ttf")
        initOrderRcy()
        initFoodRecyclerView()
        mVersionNameTv.text = "版本:".plus(CommUtils.getAppVersionName().plus("::").plus(CommUtils.getAppUUidLast4()))

    }

    private fun initOrderRcy() {
        (mHadChooseRecyclerView.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false //去闪烁
        mHadChooseAdapter = HadChooseAdapter()
        mHadChooseRecyclerView.layoutManager = LinearLayoutManager(this)
        mHadChooseRecyclerView.adapter = mHadChooseAdapter
        mHadChooseAdapter.bindToRecyclerView(mHadChooseRecyclerView)
        mHadChooseAdapter.setEmptyView(R.layout.layout_status_layout_manager_empty3)

    }

    private fun initFoodRecyclerView() {
        (mProductRecyclerView.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false //去闪烁
        mFoodAdapter = FoodAdapter()
        mProductRecyclerView.layoutManager = GridLayoutManager(this, 2)
        mProductRecyclerView.adapter = mFoodAdapter
        mFoodAdapter.bindToRecyclerView(mProductRecyclerView)
        mFoodAdapter.setEmptyView(R.layout.layout_status_layout_manager_empty1)


    }


    @SuppressLint("SetTextI18n", "CheckResult")
    private fun initFoodData(list: MutableList<ProductBean>?) {
        mTotalFoodList = list
        mTotalFoodMap.clear()

        if (mTotalFoodList != null && mTotalFoodList!!.isNotEmpty()) {
            mMaxPageCount = mTotalFoodList!!.size / mPerPageMaxCount

            //先处理整除的数据
            for (i in 0 until mMaxPageCount) {
                var tmpList = mutableListOf<ProductBean>()
                for (j in i * mPerPageMaxCount until i * mPerPageMaxCount + mPerPageMaxCount) {
                    tmpList.add(mTotalFoodList!![j])
                }
                mTotalFoodMap[i] = tmpList
            }

            //后处理除以剩下的数据
            var tmp = mTotalFoodList!!.size % mPerPageMaxCount
            d("余数多少：$tmp")
            if (tmp > 0) {
                var tmpList = mutableListOf<ProductBean>()

                for (i in mMaxPageCount * mPerPageMaxCount until mMaxPageCount * mPerPageMaxCount + tmp) {
                    tmpList.add(mTotalFoodList!![i])
                }
                mTotalFoodMap[mMaxPageCount] = tmpList
                mMaxPageCount += 1
            }

            mFoodIndexTv.text = (mCurFoodPageIndex + 1).toString()
            mFoodAdapter.setNewData(mTotalFoodMap[mCurFoodPageIndex])
        } else {
            mFoodIndexTv.text = (mCurFoodPageIndex + 1).toString()
            mFoodAdapter.setNewData(null)
        }
        d("mCurFoodListIndex:$mCurFoodPageIndex,mMaxPageCount:$mMaxPageCount")
        mLastPageTv.setOnClickListener {
            d("mCurFoodListIndex:$mCurFoodPageIndex,mMaxPageCount:$mMaxPageCount")
            if (mCurFoodPageIndex <= 0) {
                ToastUtil.showToast("没有上一页了!")
                return@setOnClickListener
            }
            mCurFoodPageIndex -= 1
            mFoodIndexTv.text = (mCurFoodPageIndex + 1).toString()
            mFoodAdapter.setNewData(mTotalFoodMap[mCurFoodPageIndex])
        }
        mNextPageTv.setOnClickListener {
            d("mCurFoodListIndex:$mCurFoodPageIndex,mMaxPageCount:$mMaxPageCount")
            if (mCurFoodPageIndex >= mMaxPageCount - 1) {
                ToastUtil.showToast("没有下一页了!")
                return@setOnClickListener
            }
            mCurFoodPageIndex += 1
            mFoodIndexTv.text = (mCurFoodPageIndex + 1).toString()
            mFoodAdapter.setNewData(mTotalFoodMap[mCurFoodPageIndex])
        }

    }

    @SuppressLint("CheckResult", "ClickableViewAccessibility")
    override fun initListener() {
        CommUtils.getAppUUid()
        mFoodIndexTv.setOnClickListener {
            //TODO:测试置零，后期记得删除
            WeightAll.setZero()
        }
        mGo2CollectMoneyTv.setOnClickListener {
            if (mCurLocalOrderBean.productList == null || mCurLocalOrderBean.productList!!.isEmpty()) {
                ToastUtil.showToast("过秤记录为空!")
                return@setOnClickListener
            }
            if (DataApi.mBuyerInfo == null) {
                ToastUtil.showToast("请买家登录!")
                return@setOnClickListener
            }

            ARouter.getInstance()
                .build(ARouterUtils.CollectMoneyActivity24)
                .withString("mDataJson", CommUtils.gson.toJson(mCurLocalOrderBean))
                .navigation()
        }
        RxView.clicks(mSellerLoginTv)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                ARouter.getInstance()
                    .build(ARouterUtils.LoginActivity24)
                    .withInt("mIdType", LOGIN_ID_TYPE_SELLER)
                    .navigation()
            }
        RxView.clicks(mBuyerLoginTv)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                ARouter.getInstance()
                    .build(ARouterUtils.LoginActivity24)
                    .withInt("mIdType", LOGIN_ID_TYPE_BUYER)
                    .navigation()
            }
        RxView.clicks(mMenuLayout)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                if (DataApi.mSellerInfo == null) {
                    ToastUtil.showToast("请卖家登录!")
                    return@subscribe
                }
                ARouter.getInstance()
                    .build(ARouterUtils.FunctionMenuActivity24)
                    .navigation()
            }
        RxView.clicks(mLoginOutLayout)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                AlertDialog.Builder(this@IndexActivity24)
                    .setMessage("是否退出登录？")
                    .setCancelable(false)
                    .setPositiveButton("确认") { dialog, _ ->
                        CommUtils.logout(this@IndexActivity24)
                        dialog.dismiss()
                    }
                    .setNegativeButton("取消") { dialog, _ -> dialog.dismiss() }
                    .show().apply {
                        DialogUtil.hideNavigationBar(this.window)
                    }
            }
        RxView.clicks(mSellerLogoutTv)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                mSellerLoginTv.visibility = View.VISIBLE
                mSellerLayout.visibility = View.GONE
                DataApi.mSellerInfo = null
                mMarketNameTv.text = ""
                mSelectedProductBean = null
                mFoodAdapter.setNewData(null)
            }
        RxView.clicks(mBuyerLogoutTv)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                mBuyerLoginTv.visibility = View.VISIBLE
                mBuyerLayout.visibility = View.GONE
                DataApi.mBuyerInfo = null
            }
        RxView.clicks(mSelectedProductClearTv)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                var index = mHadChooseAdapter.data.indices.find {
                    mHadChooseAdapter.data[it].isSelectedLocal
                }
                if (index == null) {
                    ToastUtil.showToast("请选择记录")
                    return@subscribe
                }
                AlertDialog.Builder(this@IndexActivity24)
                    .setMessage("是否删除此记录？")
                    .setCancelable(false)
                    .setPositiveButton("确认") { dialog, _ ->
                        mHadChooseAdapter.remove(index)
                        clearSelectedProductInfo()
                        dialog.dismiss()
                    }
                    .setNegativeButton("取消") { dialog, _ -> dialog.dismiss() }
                    .show().apply {
                        DialogUtil.hideNavigationBar(this.window)
                    }
            }
        KeyboardUtil.onNumberDecimalKeyDown(this, mSelectedProductPriceEt, object : OnMyKeyCallBack() {
            @SuppressLint("NotifyDataSetChanged")
            override fun onKeyEnter() {
                mSelectedHadProductBean?.productUnitPrice = String.format(
                    "%.2f", try {
                        mSelectedProductPriceEt.text.toString().trim().toDouble()
                    } catch (e: Exception) {
                        d("mSelectedProductPriceEt->onKeyEnter->error:$e")
                        0.0
                    }
                )
                d("mSelectedProductPriceEt->onKeyEnter->${mSelectedHadProductBean?.productUnitPrice}")
                mHadChooseAdapter.notifyDataSetChanged()
                calcTotalPriceAndWeight()
            }
        })//处理输入商品价格按键,关联键盘
    }

    private fun clearSelectedProductInfo() {
        mSelectedProductNameTv.text = ""
        mSelectedProductPriceEt.setText("")
        mSelectedProductSpecTv.text = ""
        mSelectedProductPeelTv.text = ""
        mSelectedProductStatusTv.text = ""
        mSelectedHadProductBean = null
    }

    /*商品列表 适配器*/
    inner class FoodAdapter : BaseItemDraggableAdapter<ProductBean, BaseViewHolder>(R.layout.item_index_good_info24, null) {
        @SuppressLint("CheckResult", "NotifyDataSetChanged")
        override fun convert(helper: BaseViewHolder, item: ProductBean) {
            helper
                .setText(R.id.item_tv1, (helper.bindingAdapterPosition + 1).toString())
                .setText(R.id.item_tv2, item.productName.plus(ProductBean.getSpecsProductName2Item(item.productSpecs)))
                .getView<ImageView>(R.id.item_iv).apply {
                    //d("商品地址:${item.productImage}")
                    ImageManger.setCenterCropImg(this@IndexActivity24, item.productImage, this, 300, R.drawable.empty_food_default1)
                }

            helper.getView<View>(R.id.item_root_view).apply {
                isSelected = item.isSelectedLocal
                setOnClickListener {
                    var productDB = mData[helper.bindingAdapterPosition]
                    var batchIdList = productDB.batchId?.split(",")

                    if (batchIdList == null) {
                        ToastUtil.showToast("批次id为空!")
                        return@setOnClickListener
                    }

                    when {
                        batchIdList.size > 1 -> {
                            //d("批处理id:${productDB.batchId}")
                            NormalApi24.getProductBatch(productDB.batchId)
                                .compose(RxUtils.aLifecycle(this@IndexActivity24))
                                .subscribe(object : DialogObserver<MutableList<ProductBean>>(this@IndexActivity24) {
                                    override fun onSuccessNext(t: BaseBean<out MutableList<ProductBean>>) {
                                        var list = t.data!!

                                        if (mSelectedBatchDialog == null) mSelectedBatchDialog = SelectedBatchDialog(this@IndexActivity24)
                                        mSelectedBatchDialog?.show()
                                        mSelectedBatchDialog?.setSelectedBatchDialogListener(object : SelectedBatchDialog.SelectedBatchDialogListener {
                                            override fun onConfirm(item: ProductBean) {
                                                mSelectedProductBean = CommUtils.gson.fromJson(CommUtils.gson.toJson(productDB), ProductBean::class.java)
                                                mSelectedProductBean?.isSelectedLocal = false
                                                mSelectedProductBean?.batchId = item.id
                                                mSelectedBatchDialog?.dismiss()

                                                //这里还需要判断是否 1定装、2非定装、3散装
                                                if (ProductBean.isDingInstall(mSelectedProductBean?.productSpecs)) {
                                                    if (mEditProductInfoDialog == null) mEditProductInfoDialog = EditProductInfoDialog(this@IndexActivity24)
                                                    mEditProductInfoDialog?.show()
                                                    mEditProductInfoDialog?.setEditProductInfoDialogListener(object : EditProductInfoDialog.EditProductInfoDialogListener {
                                                        override fun onConfirm(item: ProductBean?) {
                                                            mSelectedProductBean?.isSelectedLocal = false
                                                            mHadChooseAdapter.addData(item!!)
                                                            calcTotalPriceAndWeight()
                                                            putWeightLog(item)
                                                            mEditProductInfoDialog?.dismiss()
                                                        }
                                                    })
                                                    mEditProductInfoDialog?.setNewData(mSelectedProductBean)
                                                }
                                            }
                                        })
                                        //
                                        mSelectedBatchDialog?.setNewData(list)
                                        updateSelectedFoodUI(productDB)
                                    }
                                })
                        }
                        batchIdList.size == 1 -> {
                            mSelectedProductBean = CommUtils.gson.fromJson(CommUtils.gson.toJson(productDB), ProductBean::class.java)
                            mSelectedProductBean?.isSelectedLocal = false
                            updateSelectedFoodUI(productDB)
                        }
                        else -> ToastUtil.showToast("批次id为空!")
                    }
                }
            }
        }

        @SuppressLint("NotifyDataSetChanged")
        private fun updateSelectedFoodUI(productDB: ProductBean) {
            mTotalFoodList?.forEach { it.isSelectedLocal = false }
            productDB.isSelectedLocal = true
            mFoodAdapter.notifyDataSetChanged()
        }
    }

    /*购物车列表 适配器*/
    inner class HadChooseAdapter : BaseQuickAdapter<ProductBean, BaseViewHolder>(R.layout.item_order_list24, null) {
        @SuppressLint("CheckResult", "NotifyDataSetChanged")
        override fun convert(helper: BaseViewHolder, item: ProductBean) {
            helper
                .setText(R.id.item_tv1, (mData.size - helper.bindingAdapterPosition).toString())
                .setText(R.id.item_tv2, item.productName)
                .setText(R.id.item_tv3, String.format("%.1f", item.roughWeight))
                .setText(R.id.item_tv4, String.format("%.1f", item.peelWeight))
                .setText(R.id.item_tv5, String.format("%.1f", item.netWeight))
                .setText(R.id.item_tv6, item.status.toString())
                .setText(R.id.item_tv7, item.productSpecs.toString())
                .getView<View>(R.id.item_root_view)
                .apply {
                    isSelected = item.isSelectedLocal
                    setOnClickListener {
                        mData.forEach { it.isSelectedLocal = false }
                        mSelectedHadProductBean = mData[helper.bindingAdapterPosition]
                        mSelectedHadProductBean?.isSelectedLocal = true
                        notifyDataSetChanged()

                        //刷新右边东西
                        mSelectedProductNameTv.text = item.productName
                        mSelectedProductPriceEt.setText(item.productUnitPrice)
                        mSelectedProductSpecTv.text = item.productSpecs.toString()
                        mSelectedProductPeelTv.text = String.format("%.1f", item.peelWeight)
                        mSelectedProductStatusTv.text = item.status.toString()
                    }
                }
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        //return if (KeyboardUtil.onKeyDown(keyCode, event, this)) true else super.onKeyDown(keyCode, event)
        if (event?.device?.name?.contains("USB", true) != true) return false
        if (event.action == KeyEvent.ACTION_DOWN) {//处理触发两次
            when (keyCode) {
                //第一行
                33 -> {
                    d("帐户/E")
                    mMenuLayout.performClick()
                    return true
                }
                133 -> {
                    d("删除/F3")
                    mSelectedProductClearTv.performClick()
                    return true
                }
                32 -> {
                    d("修改/D")
                    return true
                }
                134 -> {
                    d("挂起/F4")
                    return true
                }

                //第二行
                46 -> {
                    d("回皮/E")
                    onBackPeelClick()
                    return true
                }
                48 -> {
                    d("1/T")
                    return true
                }
                34 -> {
                    d("2/F")
                    //activity?.onKeyDown(KeyEvent.KEYCODE_2, event)
                    return true
                }
                35 -> {
                    d("3/G")
                    return true
                }

                //第三行
                49 -> {
                    d("回毛/U")
                    onBackRoughClick()
                    return true
                }
                53 -> {
                    d("4/Y")
                    return true
                }
                38 -> {
                    d("5/J")
                    return true
                }
                36 -> {
                    d("6/H")
                    return true
                }

                //第四行
                37 -> {
                    d("去皮/I")
                    WeightAll.setPeel()
                    return true
                }
                72 -> {
                    d("7/]")
                    return true
                }
                39 -> {
                    d("8/K")
                    return true
                }

                //第五行
                153 -> {
                    d("清皮/9")
                    WeightAll.clearPeel()
                    return true
                }
                158 -> {
                    d("过称/.")
                    //WeightAll.setZero()
                    onWeightClick()
                    return true
                }

                //第六行
                152 -> {
                    d("↑/8")
                    mLastPageTv.performClick()
                    return true
                }
                149 -> {
                    d("F1/5")
                    return true
                }
                146 -> {
                    d("F2/2")
                    return true
                }
                144 -> {
                    d("F3/0")
                    return true
                }

                //第七行
                44 -> {
                    d("↓/P")
                    mNextPageTv.performClick()
                    return true
                }
                71 -> {
                    d("F4/[")
                    return true
                }
                74 -> {
                    d("F5/;")
                    return true
                }
                75 -> {
                    d("确认/'")
                    mGo2CollectMoneyTv.performClick()
                    return true
                }
            }
        }
        return super.onKeyDown(keyCode, event)
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun onBackRoughClick() {
        if (mIsStable) {
            if (mSelectedHadProductBean != null) {
                mSelectedHadProductBean?.roughWeight = mWeightDouble//刷新毛重
                //皮重不变，净重= 毛重-皮重。
                mSelectedHadProductBean?.netWeight = (mWeightDouble - (mSelectedHadProductBean?.peelWeight ?: 0.0)).toString().toDoubleWithTwoDecimalPlaces(DECIMAL_POINT_NUMBER1)//净重
                mHadChooseAdapter.notifyDataSetChanged()
                calcTotalPriceAndWeight()
                putWeightLog(mSelectedHadProductBean)
            } else {
                ToastUtil.showToast("请选择过称记录!")
            }
        } else {
            ToastUtil.showToast("状态不稳定!")
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun onBackPeelClick() {
        if (mIsStable) {
            if (mSelectedHadProductBean != null) {
                mSelectedHadProductBean?.peelWeight = mWeightDouble//刷新皮重

                //毛重不变，净重 = 毛重-皮重

                mSelectedHadProductBean?.netWeight = ((mSelectedHadProductBean?.roughWeight ?: 0.0) - mWeightDouble).toString().toDoubleWithTwoDecimalPlaces(DECIMAL_POINT_NUMBER1)//净重

                mHadChooseAdapter.notifyDataSetChanged()
                calcTotalPriceAndWeight()
                putWeightLog(mSelectedHadProductBean)
            } else {
                ToastUtil.showToast("请选择过称记录!")
            }
        } else {
            ToastUtil.showToast("状态不稳定!")
        }
    }

    private fun putWeightLog(selectedHadProductBean: ProductBean?) {
        try {
            var newSelectedHadProductBean = CommUtils.gson.fromJson(CommUtils.gson.toJson(selectedHadProductBean), ProductBean::class.java)
            var subTotal = newSelectedHadProductBean.netWeight * (newSelectedHadProductBean.productUnitPrice?.toDouble() ?: 0.0)
            newSelectedHadProductBean.subTotalPrice = subTotal.toString().toDoubleWithTwoDecimalPlaces()
            NormalApi24.putWeightLog(newSelectedHadProductBean)
                .compose(RxUtils.aLifecycle(this))
                .subscribe(object : NormalObserver<PayResultBean>() {
                    override fun onSuccessNext(t: BaseBean<out PayResultBean>) {
                    }
                })
        } catch (e: Exception) {
            d("过程流水error:$e")
        }
    }

    /*过秤操作*/
    private fun onWeightClick() {
        if (mIsStable) {
            if (mSelectedProductBean != null) {
                if (!ProductBean.isDingInstall(mSelectedProductBean?.productSpecs)) {
                    mSelectedProductBean?.roughWeight = mWeightDouble
                    mSelectedProductBean?.peelWeight = mWeightDouble
                    mSelectedProductBean?.netWeight = 0.0
                    mSelectedProductBean?.isSelectedLocal = false

                    //mSelectedProductBean?.isGoWeight = true
                    mHadChooseAdapter.addData(mSelectedProductBean!!)

                    calcTotalPriceAndWeight()
                } else {
                    ToastUtil.showToast("${ProductBean.getSpecsProductName(mSelectedProductBean?.productSpecs)}商品不能过秤!")
                }
            } else {
                ToastUtil.showToast("请选择商品!")
            }
        } else {
            ToastUtil.showToast("状态不稳定!")
        }
    }

    /*计算结算金额*/
    @SuppressLint("SetTextI18n")
    private fun calcTotalPriceAndWeight() {
        var totalPrice = BigDecimal(0.0)

        var totalRoughWeight = BigDecimal(0.0)
        var totalPeelWeight = BigDecimal(0.0)
        var totalNetWeight = BigDecimal(0.0)

        mHadChooseAdapter.data.forEach {
            totalPrice = try {
                var subTotal = it.netWeight * (it.productUnitPrice?.toDouble() ?: 0.0)
                it.subTotalPrice = subTotal.toString().toDoubleWithTwoDecimalPlaces()
                UtilsBigDecimal.add(totalPrice, subTotal)
            } catch (e: Exception) {
                ToastUtil.showToast("结算金额异常:$e")
                BigDecimal(0.0)
            }

            totalRoughWeight = try {
                UtilsBigDecimal.add(totalRoughWeight, it.roughWeight)
            } catch (e: Exception) {
                ToastUtil.showToast("计算总毛重异常:$e")
                BigDecimal(0.0)
            }
            totalPeelWeight = try {
                UtilsBigDecimal.add(totalPeelWeight, it.peelWeight)
            } catch (e: Exception) {
                ToastUtil.showToast("计算总皮重异常:$e")
                BigDecimal(0.0)
            }
            totalNetWeight = try {
                UtilsBigDecimal.add(totalNetWeight, it.netWeight)
            } catch (e: Exception) {
                ToastUtil.showToast("计算总净重异常:$e")
                BigDecimal(0.0)
            }
        }
        mCurLocalOrderBean.hangId = mHadChooseAdapter.data.firstOrNull()?.hangId
        mCurLocalOrderBean.productList = mHadChooseAdapter.data
        mCurLocalOrderBean.totalPrice = String.format("%.2f", totalPrice)
        mCurLocalOrderBean.totalWeightRough = String.format("%.2f", totalRoughWeight)
        mCurLocalOrderBean.totalWeightPeel = String.format("%.2f", totalPeelWeight)
        mCurLocalOrderBean.totalWeightNet = String.format("%.2f", totalNetWeight)

        mGo2CollectMoneyTv.text = "结算(${mCurLocalOrderBean.totalPrice})"
        mTotalRoughWeightAtv.text = mCurLocalOrderBean.totalWeightRough
        mTotalPeelWeightAtv.text = mCurLocalOrderBean.totalWeightPeel
        mTotalNetWeightAtv.text = mCurLocalOrderBean.totalWeightNet
    }

    override fun isRegisterEventBus(): Boolean = true

    @SuppressLint("SetTextI18n", "NotifyDataSetChanged")
    override fun receiveEvent(event: Event<Any>) {
        super.receiveEvent(event)
        when (event.code) {
            EventCode.WEIGHT_DATA_ALL -> {//称重数据
                var weightData = event.data as WeightBean
                mWeightTv.setTextColor(CommUtils.getColor(R.color.red_count_num))
                mWeightTv.text = weightData.weightString
                mIsStable = weightData.isStable
                mWeightDouble = weightData.weightDouble
                mStableTv.visibility = if (weightData.isStable) View.VISIBLE else View.INVISIBLE
                EventBusUtil.sendEvent(Event(EventCode.VICE_SCREEN_WEIGHT_NUMBER, mWeightTv.text.toString()))
            }
            EventCode.LOGIN_SUCCESS_SELLER -> {//卖家登陆成功
                mSellerLoginTv.visibility = View.GONE
                mSellerLayout.visibility = View.VISIBLE

                mSellerNameTv.text = DataApi.mSellerInfo?.merchantList?.firstOrNull()?.personName
                mSellerInfoTv.text = "服务费：${DataApi.mMerchantServiceFee}%"
                mMarketNameTv.text = "市场名称：${DataApi.mSellerInfo?.bazaarList?.firstOrNull()?.bazaarName ?: ""}"
                //获取菜品
                getProductList()
            }
            EventCode.LOGIN_SUCCESS_BUYER -> {//买家登陆成功
                mBuyerLoginTv.visibility = View.GONE
                mBuyerLayout.visibility = View.VISIBLE

                mBuyerNameTv.text = DataApi.mBuyerInfo?.buyerName
                mBuyerInfoTv.text = "服务费：${DataApi.mBuyServiceFee}%"
            }
            EventCode.PAY_SUCCESS_NORMAL, HANG_SUCCESS -> {//支付\挂单成功
                mSelectedProductBean?.isSelectedLocal = false
                mSelectedProductBean = null
                mFoodAdapter.notifyDataSetChanged()//按需清除
                mHadChooseAdapter.setNewData(null)
                clearSelectedProductInfo()
                calcTotalPriceAndWeight()
            }
            EventCode.HANG_GO_COLLECT -> {
                mSelectedProductBean?.isSelectedLocal = false
                mSelectedProductBean = null
                mFoodAdapter.notifyDataSetChanged()//按需清除
                var newHadList = event.data as MutableList<ProductBean>
                newHadList.firstOrNull()?.isSelectedLocal = true
                mHadChooseAdapter.setNewData(newHadList)
                clearSelectedProductInfo()
                calcTotalPriceAndWeight()
            }
        }
    }

    private fun getProductList() {
        NormalApi24.getProduct()
            .compose(RxUtils.aLifecycle(this))
            .subscribe(object : StatusLayoutObserver<MutableList<ProductBean>>(this, mProductStatusLayoutManager) {
                override fun onSuccessNext(t: BaseBean<out MutableList<ProductBean>>) {
                    mProductStatusLayoutManager.showSuccessLayout()
                    initFoodData(t.rows)
                }
            })
    }

    override fun doubleQuit(): Boolean = true
    override fun exit(): Boolean {
        try {
            if (isExit) {
                stopService(Intent(this, AppService::class.java))
                //stopService(Intent(this, RemoteService::class.java))
                //stopService(Intent(this, LocalService::class.java))
            }
        } catch (e: Exception) {
            d("退出失败:$e")
        }
        return super.exit()
    }

}

/*
*
*
刷卡批发秤操作流程：
注意：重量超过20斤就只显示0.0。取消订单需要市场方拿管理卡取消。随时可以按挂起键退出交易界面。毛重=皮重+净重。
有两种操作方法：
方法一：先称皮重，再称毛重。
买卖双方分别刷卡，不分先后。用手点击app上面的鱼的品类，先称装水的水桶，app出现"稳”字，按“过称”键，app会记录一条订单，然后开始让水桶里面放鱼，放完后，用手指点击那条订单选中它。等app出现“稳”字，按“回毛”键（回去称毛重的意思）。这时就算出鱼的重量。按“确定”键弹出订单给双方核对，再按确认就提交订单。
简单概括：过称，回毛，确认，确认。

方法二：先称毛重，再称皮重。
买卖双方分别刷卡，不分先后。用手点击app上面的鱼的品类，先称装满的水桶，app出现"稳”字，按“过称”键，app会记录一条订单，然后把水桶里面的鱼捞出来，捞完后，用手指点击那条订单选中它。等app出现“稳”字，按“回皮”键（回去称皮重的意思）。这时就算出鱼的重量。按“确定”键弹出订单给双方核对，再按确认就提交订单。
简单概括：过称，回皮，确认，确认。

水产秤操作逻辑：
1、买卖双方分别刷卡或者登录，不分先后
2、选品/称重/改单价：先选品名再放商品到秤盘。或者。先放商品到秤盘再选品名
3、过秤：按键盘的“过秤”键。（获取毛重或皮重，同时上传数据）
4、计算净重：再按“回毛”或者“回皮”（计算出商品的净重。毛重=皮重+净重）
5、结算订单：按“确认”键核对订单，再按“确认”结算订单

注意事项：
（1）若是公秤，重量超过20斤就只显示0.0。按了“过称”键后，屏幕显示实际重量（净重）持续2~3秒钟，这时候，app已记录这个重量，然后恢复显示0.0（目的是不想让买卖双方知道防止私下交易）；按设备控制是否超过XX斤就显示0.0，后台做成配置
（2）app显示，需要把市斤考虑在内（秤体只传公斤数据，app显示x2倍，上传数据也是按公斤来上传）；按设备后台做成配置
（3）若是公秤，按键“去皮”；可以控制不给使用，按设备后台做成配置
（4）秤的按键F1~F5，为自定义键
*
* */